package com.alvis.media.controller.admin;

import com.alvis.media.base.BaseApiController;
import com.alvis.media.base.RestResponse;
import com.alvis.media.base.SystemCode;
import com.alvis.media.constant.UserConstant;
import com.alvis.media.domain.other.KeyValue;
import com.alvis.media.domain.User;
import com.alvis.media.domain.UserEventLog;
import com.alvis.media.domain.enums.UserStatusEnum;
import com.alvis.media.service.AuthenticationService;
import com.alvis.media.service.UserEventLogService;
import com.alvis.media.service.UserService;
import com.alvis.media.utility.DateTimeUtil;
import com.alvis.media.utility.PageInfoHelper;
import com.alvis.media.viewmodel.admin.user.*;
import com.github.pagehelper.PageInfo;
import lombok.AllArgsConstructor;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 后台普通用户列表
 */
// @RestController = @Controller + @ResponseBody -> 传输JSON数据
@RestController("AdminUserController")
@RequestMapping(value = "/api/admin/user")
@AllArgsConstructor
public class UserController extends BaseApiController {

    /**
     * 普通用户Service
     */
    @Autowired
    private final UserService userService;
    /**
     * 普通用户日志Service
     */
    private final UserEventLogService userEventLogService;
    /**
     * 权限Service
     */
    private final AuthenticationService authenticationService;

    /**
     * 查询用户列表方法
     * @param model 查询条件（根据用户名称）
     * @return RestResponse<PageInfo<UserResponseVM>> 带分页的用户信息列表
     */

    @RequestMapping(value = "/page/list", method = RequestMethod.POST)
    public RestResponse<PageInfo<UserResponseVM>> pageList(@RequestBody UserPageRequestVM model) {
        PageInfo<User> pageInfo = userService.userPage(model);
        //PageInfo<User> pageInfo --》 转换成 PageInfo<UserResponseVM> page
        //UserResponse页面要展示的内容
        PageInfo<UserResponseVM> page = PageInfoHelper.copyMap(pageInfo, d -> UserResponseVM.from(d));
        return RestResponse.ok(page); //响应JSON数据给前台页面
    }


    @RequestMapping(value = "/event/page/list", method = RequestMethod.POST)
    public RestResponse<PageInfo<UserEventLogVM>> eventPageList(@RequestBody UserEventPageRequestVM model) {
        PageInfo<UserEventLog> pageInfo = userEventLogService.page(model);
        PageInfo<UserEventLogVM> page = PageInfoHelper.copyMap(pageInfo, d -> {
            UserEventLogVM vm = modelMapper.map(d,UserEventLogVM.class);
            vm.setCreateTime(DateTimeUtil.dateFormat(d.getCreateTime()));
            return vm;
        });
        return RestResponse.ok(page);
    }

    @RequestMapping(value = "/select/{id}", method = RequestMethod.POST)
    public RestResponse<UserResponseVM> select(@PathVariable Integer id) {
        //User user = userService.selectById(id);

        User user = userService.getUserById(id);
        UserResponseVM userVm = UserResponseVM.from(user);
        return RestResponse.ok(userVm);

        //实际开发中不允许
//        Integer newUserStatus = user.getStatus() == 1?2:1;
//        if (user.getStatus() == 1){
//            user.setStatus(2);
//        }else {
//            user.setStatus(1);
//        }
//
//        user.setModifyTime(new Date());
//        userService.updateByIdFilter(user);//调用修改方法
//
//        return RestResponse.ok(UserResponseVM.from(user));
    }

    @RequestMapping(value = "/current", method = RequestMethod.POST)
    public RestResponse<UserResponseVM> current() {
        User user = getCurrentUser();
        UserResponseVM userVm = UserResponseVM.from(user);
        return RestResponse.ok(userVm);
    }

    /**
     * 新增用户 和 修改用户 功能（如果有用户表的主键值就是编辑用户）
     * @param model 用户在前台页面输入的数据，传递到后台
     * @return RestResponse.ok(user) 响应数据给前台页面
     */
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public RestResponse<User> edit(@RequestBody @Valid UserCreateVM model) {

        if (model.getId() == null) { //create
            User existUser = userService.getUserByUserName(model.getUserName());
            if (null != existUser) {
                return new RestResponse<>(2, "用户不存在");
            }
            if (StringUtils.isBlank(model.getPassword())) {
                return new RestResponse<>(3, "密码不能为空");
            }
        }

        if (StringUtils.isBlank(model.getBirthDay())) {
            model.setBirthDay(null);
        }

        User user = modelMapper.map(model, User.class);

        if (model.getId() == null) {
            String encodePwd = authenticationService.pwdEncode(model.getPassword());
            user.setPassword(encodePwd);
            user.setUserUuid(UUID.randomUUID().toString());
            user.setCreateTime(new Date());
            user.setLastActiveTime(new Date());
            user.setDeleted(false);
            userService.insertByFilter(user);
        } else {
            if (!StringUtils.isBlank(model.getPassword())) {
                String encodePwd = authenticationService.pwdEncode(model.getPassword());
                user.setPassword(encodePwd);
            }
            user.setModifyTime(new Date());
            userService.updateByIdFilter(user);
        }
        return RestResponse.ok(user);
    }


    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public RestResponse update(@RequestBody @Valid UserUpdateVM model) {
//        User user = userService.selectById(model.getId());
//        if (user == null) {
//            // 注意：这里之前的fail方法需要两个参数，参考上一次修改
//            return RestResponse.fail(SystemCode.ParameterValidError.getCode(), "用户不存在");
//        }
//        user.setRealName(model.getRealName());
//        user.setPhone(model.getPhone());
//        userService.updateByIdFilter(user);
//        return RestResponse.ok();
        User user = userService.selectById(getCurrentUser().getId());
        modelMapper.map(model,user);
        user.setModifyTime(new Date());
        userService.updateByIdFilter(user);
        return RestResponse.ok();
    }

    /**
     * 启用/禁用代码
     * @param id 要启用/禁用的某条用户记录的主键（用户编号）值 修改T_USER表中status 1 启用 2 禁用
     * @return 响应对应的JSON数据给页面
     */
    @RequestMapping(value = "/changeStatus/{id}", method = RequestMethod.POST)
    public RestResponse<Integer> changeStatus(@PathVariable Integer id) {
        //根据用户编号查询某个用户信息
        User user = userService.getUserById(id);

        //实际开发中
        Integer newUserStatus = user.getStatus() == UserConstant.USER_STATUS_ENABLE ? UserConstant.USER_STATUS_DISABLE : UserConstant.USER_STATUS_ENABLE;

        user.setModifyTime(new Date());//更新用户修改时间
        user.setStatus(newUserStatus);//更新用户状态
        userService.updateByIdFilter(user);//调用修改方法

        return RestResponse.ok();//把修改后的用户转态发送页面
    }

    /**
     * 删除用户（逻辑删除）
     * @param id 根据普通用户编号去修改用户信息,标记为已删除
     * @return RestResponse 删除后的JSON数据
     */
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    public RestResponse delete(@PathVariable Integer id) {
        // 根据用户编号查询某个用户信息
        User user = userService.getUserById(id);
        
        if (user == null) {
            return RestResponse.fail(SystemCode.ParameterValidError.getCode(), "用户不存在");
        }
        
        // 检查用户是否已经被删除
        if (user.getDeleted() != null && user.getDeleted()) {
            return RestResponse.fail(SystemCode.ParameterValidError.getCode(), "用户已被删除");
        }

        // 使用逻辑删除：设置deleted标志为true
        user.setDeleted(true);
        user.setModifyTime(new Date());
        
        // 执行更新操作
        int result = userService.updateByIdFilter(user);
        
        if (result > 0) {
            return RestResponse.ok(result);
        } else {
            return RestResponse.fail(SystemCode.InnerError.getCode(), "删除失败");
        }
    }


    @RequestMapping(value = "/selectByUserName", method = RequestMethod.POST)
    public RestResponse<List<KeyValue>> selectByUserName(@RequestBody String userName) {
        if (StringUtils.isEmpty(userName)) {
            return RestResponse.ok(new ArrayList<>());
        }
        User user = userService.getUserByUserName(userName);
        List<KeyValue> result = new ArrayList<>();
        if (user != null) {
            result.add(new KeyValue(user.getId().toString(), user.getUserName()));
        }
        return RestResponse.ok(result);
        //return RestResponse.ok();
    }



    @RequestMapping(value = "/getUserDetailByUserId/{id}", method = RequestMethod.POST)
    public RestResponse<UserResponseVM> getUserDetailByUserId(@PathVariable Integer id) {

        return RestResponse.ok();
    }
}
